import * as React from 'react';
import '../../static/writeArticle.css';
import '../../static/subList.css';
import '../../static/cssUnit.css';
import ListFactory from "./lib/ListFactory";
import API from 'src/API';
import SubListFactory from "./lib/SubListFactory";
import {connect} from 'react-redux';
import {IReducer} from "../../reducer";

export interface ISubListProps {
    liLists:ListFactory
    subMenuList: SubListFactory
    refreshEditor:(isEditor:boolean, subMenuIndex:number)=>void|undefined
    sublistCurrent:number
    dispatch: (data:any)=>any
    componentRefreshReduce?:any
}

export interface IState {
    isReady:boolean
}

class SubList extends React.Component<ISubListProps>{

    state:IState={
        isReady:false
    };

    //他会在所需数据准备完毕后背赋值为true
    isReady:boolean = false;
    isEditor:boolean = false;
    liListsIndex = this.props.liLists.findSelectedIndex();
    isFirstRunItemDisplay:boolean = true;

    componentDidMount(){
        this.initSubMenuListSelectState();
        this.setState({isReady:this.isReady});
    }

    initSubMenuListSelectState(){
        const liList = this.props.liLists;
        const index = liList.findSelectedIndex();
        const subMenuList = liList.list[index].subMenuList;
        const LENGTH = subMenuList.list.length;
        if(LENGTH>0){
            subMenuList.list[0].onlyDisplayOwn();
        }else{
            //TODO 这里书写子列表没有文章时的处理情况
        }
    }

    /*上传经过初始化的文章*/
    uploadInitArticle(){
        const d = new Date();
        const day = d.getUTCDate()===0?7:d.getUTCDate();
        const currentDate = String((d.getFullYear())+'-'+(d.getUTCMonth()+1)+'-'+(day));
        const liLists:ListFactory = this.props.liLists;
        const index = liLists.findSelectedIndex();
        const anthology = liLists.list[index].anthologyTitle;

        API.post.createArticle({anthology, title:currentDate, author:'coffeeCat', content:''}).
        then((result)=>{
            const subMenuList = liLists.list[index].subMenuList;
            const storeId:number = result.data.result[0].id;
            const title:string = result.data.result[0].title;

            subMenuList.push({storeId, title, wordCount:0, abstract:''});
            this.setState({});
        });
    }

    /*删除文章*/
    async deleteArticle(){
        const liLists = this.props.liLists;
        const liListsIndex = liLists.findSelectedIndex();
        const subMenuList = liLists.list[liListsIndex].subMenuList;
        const index = subMenuList.findSelectedIndex();
        if(index===-1){
            throw 'index === -1';
        }
        const storeId = subMenuList.list[index].getStoreIdSelf();
        const anthology = liLists.list[liListsIndex].anthologyTitle;
        await API.post.deleteArticle({storeId}).then((res)=>{
            return res;
        });
        await API.post.getArticleAll({author:'coffeeCat',anthology}).then((restult)=>{
            const {result} = restult.data;
            const _result = liLists.list[liListsIndex].subMenuList.extra(result);
            liLists.list[liListsIndex].subMenuList.againSetList(_result);
            return 1;
        });
        // await this.props.componentRefreshReduce[0].refreshWriteArticle();
        const {refreshWriteArticle} = this.props.componentRefreshReduce;
        await refreshWriteArticle();
        return 1;
    }

    /*显示正确的修改菜单*/
    itemModificationMenuDisplay(index: number, e: Event){
        e.stopPropagation();
        const subMenuList = this.props.liLists.list[this.liListsIndex].subMenuList;
        subMenuList.noDisplayModificationMenu();
        subMenuList.list[index].onlyDisplayOwn();
        subMenuList.list[index].onlyDisplayModificationMenuOwn();
        this.setState({});
    }

    /**
     * 显示被点击的子菜单中的条目
     * 同时上传上一篇文章的内容并从后端获取新文章
     * */
    async itemDisplay(index: number, e: Event):Promise<any>{
        e.stopPropagation();
        const subMenuList = this.props.liLists.list[this.liListsIndex].subMenuList;
        if(this.isFirstRunItemDisplay){
            return await this.getArticleContent(index, subMenuList);
        }else{
            //上传先前的文章
            const prevSubMenuIndex = subMenuList.findSelectedIndex();
            const prevStoreId = subMenuList.list[prevSubMenuIndex].storeId;
            const prevTitle = subMenuList.list[prevSubMenuIndex].markDownEditor.title;
            const prevContent = subMenuList.list[prevSubMenuIndex].markDownEditor.content;
            const prevAnthology = subMenuList.list[prevSubMenuIndex].markDownEditor.anthologyTitle;
            await API.post.uploadArticleText({
                id:prevStoreId,
                title:prevTitle,
                content:prevContent,
                anthology:prevAnthology,
                author:'coffeeCat'
            });
           return await this.getArticleContent(index, subMenuList);
        }
    }

    /*更新editor的状态*/
    async getArticleContent(index:number, subMenuList:SubListFactory){
        subMenuList.list[index].onlyDisplayOwn();
        subMenuList.noDisplayModificationMenu();
        const subMenuIndex = subMenuList.findSelectedIndex();
        subMenuList.list[subMenuIndex].markDownEditor.content = await this.getEditorContent();
        this.isEditor = true;
        this.props.refreshEditor(this.isEditor, subMenuIndex);
        return ;
    }

    /*从后端获取文章*/
    async getEditorContent():Promise<string>{
        const liLists = this.props.liLists;
        const liListsIndex = liLists.findSelectedIndex();
        const subMenuIndex = liLists.list[liListsIndex].subMenuList.findSelectedIndex();
        const id = liLists.list[liListsIndex].subMenuList.list[subMenuIndex].storeId;
        const queryResult = await  API.post.getArticleContent({id});
        const {result} = queryResult.data;
        return result
    }

    resetLiListsIndex(){
        this.liListsIndex = this.props.liLists.findSelectedIndex();
    }

    allCloseDisplayModificationMenu(){
        const subMenuList = this.props.liLists.list[this.liListsIndex].subMenuList;
        subMenuList.noDisplayModificationMenu();
    }

    render(){
        this.resetLiListsIndex();
        const subMenuList = this.props.subMenuList;
        return (
            <div className="submenu none-user-select" onClick={this.allCloseDisplayModificationMenu.bind(this)}>
                <div className={'submenu-create-article'} >
                    <span className={'submenu-plus'}/>
                    <article className={'submenu-title'}
                             onClick={this.uploadInitArticle.bind(this)}>&#xe845;新建文章</article>
                </div>
                <ul className={'submenu-items ul-init'}>
                    { subMenuList.list.map((val,index)=>{
                        return (
                            <li key={index}
                                className={val.isSelected?'submenu-item submenu-item-selected':'submenu-item'}
                                onClick={this.itemDisplay.bind(this, index)}>
                                <div className={'submenu-item-icon'}>&#xec37;</div>
                                <div className={'submenu-item-title'}>{val.title}</div>
                                <div className={'submenu-item-abstract'}>{val.abstract}</div>
                                <div className={'submenu-item-word-count'}>字数:{val.wordCount}</div>
                                <div className={'submenu-item-modification-button'}
                                     onClick={this.itemModificationMenuDisplay.bind(this, index)}>
                                    {val.isModificationMenuOpen?
                                        <ul className={'submenu-item-modification-menu ul-init'}>
                                            <li className={'submenu-item-modification-menu-item li-init'}
                                                title={'修改'}
                                                onClick={this.deleteArticle.bind(this, index)}>删除文章</li>
                                        </ul>
                                        :null}
                                    <article>&#xe60b;</article>
                                </div>
                            </li>
                        );
                    })}
                </ul>
            </div>)
    }
}

function mapStateToProps(state:IReducer){
    const {componentRefreshReduce} = state;
    return {componentRefreshReduce}
}

function mapDispatchToProps(dispatch:any) {
    return {dispatch};
}

export default connect(
    mapStateToProps,
    mapDispatchToProps,
    undefined,
    {pure:false})(SubList);
